<template>
  <div class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="调拨单号" prop="moveLocationCode">
          <CodeRuleInput :band-value.sync="formData.moveLocationCode" table-name="wms_move_location" column-name="move_location_code" :is-edit="id" />
        </el-form-item>
        <el-form-item label="调拨原因" prop="moveLocationReason">
          <DictSelect
            :band-value.sync="formData.moveLocationReason"
            dict-type="allotCause"
          />
        </el-form-item>
        <el-form-item label="调拨人员">
          <el-input v-model="formData.moveName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="调拨日期">
          <el-date-picker
            v-model="formData.moveTime"
            placeholder="请选择"
            :editable="false"
          />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            maxlength="200"
            show-word-limit
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
      </el-form>
      <div class="formItem_header">
        物料明细
        <div class="formItem_header_operate">
          <a class="formItem_header_operate_item" @click="add">
            <svg-icon icon-class="新增" />
            <div class="item_name">添加</div>
          </a>
          <!-- <a class="formItem_header_operate_item" @click="importSpareParts">
            <svg-icon icon-class="导入" />
            <div class="item_name">导入</div>
          </a> -->
          <a class="formItem_header_operate_item delete" @click="remove1">
            <svg-icon icon-class="删除" />
            <div class="item_name">删除</div>
          </a>
        </div>
      </div>
      <div ref="table_container2" class="table_container">
        <el-table
          ref="table"
          :data="formData.details"
          :height="tableHeight"
          stripe
          border
          style="width: 99.9%"
          :header-cell-class-name="headerCellClassName"
          @selection-change="selectionChange1"
        >
          <el-table-column type="selection" width="70" align="center" />
          <el-table-column label="物料编码" min-width="120" prop="materialCode" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialModel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料分类" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialTypeName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="批号" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.palletBatchCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="调出仓库" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.sourceWarehouseName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="调出库位" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.sourceLocationName }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="物料单位" min-width="130">
            <template slot-scope="scope">
              <span>{{ scope.row.materialUnitName }}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="库存数量" :min-width="SETTINGS.settings_decimalDigits_length">
            <template slot-scope="scope">
              <span>{{ scope.row.stockNum }}</span>
            </template>
          </el-table-column>
          <el-table-column label="调拨数量" fixed="right" :min-width="SETTINGS.settings_decimalDigits_length" prop="moveNum">
            <template slot-scope="scope">
              <el-input v-model="scope.row.moveNum" placeholder="请输入" clearable />
            </template>
          </el-table-column>
          <el-table-column label="调入仓库" fixed="right" width="150" prop="targetWarehouseName">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.targetWarehouseName"
                readonly
                placeholder="请选择"
                clearable
                @click.native="enterWarehouse(scope.row,scope.$index)"
              />
            </template>
          </el-table-column>
          <el-table-column label="调入库位" fixed="right" min-width="150" prop="targetLocationName">
            <template slot-scope="scope">
              <!--              <el-input-->
              <!--                v-model="scope.row.targetLocationName"-->
              <!--                readonly-->
              <!--                placeholder="请选择"-->
              <!--                clearable-->
              <!--                @click.native="enterWarehouseLocation(scope.row,scope.$index)"-->
              <!--              />-->
              <el-select v-model="scope.row.targetLocationId" :disabled="!scope.row.targetWarehouseName" filterable clearable placeholder="请选择">
                <el-option
                  v-for="item in scope.row.locationOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入" clearable />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="save('0')">保存</el-button>
      <el-button @click.stop="onSubmit('1')">提交</el-button>
    </div>
  </div>
</template>
<script>
import { addOrUpdate, getInfo } from '@/api/warehouseManagement/allotWarehouse'
import searchMaterial from './addWarehouseInventory.vue'
import moment from 'moment'
import ImportData from '@/components/JLink/common/ImportData'
import warehouseLocation from '../storageModeling/warehouseLocation'
import warehouse from '../warehouseModeling/warehouse'
import { list, list as getWarehouseLocation } from '@/api/warehouseManagement/storageModeling'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {}
  },
  data() {
    return {
      formData: {
        id: undefined,
        moveLocationCode: undefined,
        moveLocationReason: undefined,
        moveBy: undefined,
        moveName: undefined,
        moveTime: undefined,
        remark: undefined,
        status: '0',
        details: []
      },
      listData: [],
      tableHeight: '318',
      userOptions: [],
      equipmentList: [],
      selectionsAll1: [],
      ids: [],
      roleOptions: [],
      selectionsAll: [], // 表格所有页选中的行
      inx: 1,
      listDate: [],
      rules: {
        moveLocationReason: [
          { required: true, message: '调拨原因不能为空', trigger: 'change' }
        ],
        moveLocationCode: [
          { required: true, message: '调拨单号不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    if (!this.id) { // 没有id就是新增
    } else { // 有id就是编辑
      this.getInfo()
    }
  },
  mounted() {
    this.formData.moveName = this.$store.state.user.name
    this.formData.moveBy = this.$store.state.user.userId
    this.formData.moveTime = moment(new Date()).format('YYYY-MM-DD')
  },
  methods: {
    headerCellClassName(data) {
      if (['moveNum', 'targetWarehouseName', 'targetLocationName'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    selectionChange1(rows) {
      this.selectionsAll1 = rows
    },
    getInfo() {
      getInfo(this.id).then(res => {
        this.formData = res.data
        this.formData.roleIdsArray = this.formData.roleIds ? this.formData.roleIds.split(',') : ''
        this.formData.details.filter((item, index) => {
          this.getLocationList({ warehouseId: item.targetWarehouseId, rowIndex: index, checked: false })
        })
      })
    },
    remove1() {
      this.selectionsAll1.forEach(item => {
        this.formData.details.splice(this.formData.details.indexOf(item), 1)
      })
    },
    add() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: searchMaterial, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: this.formData.details ? this.formData.details : []
          } // props
        },
        area: ['1020px', '650px'],
        title: '选择物料', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    onSubmit(number) {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.formData.status = number
          if (this.formData.details.length == 0) {
            this.$message.warning('请添加物料明细')
            return
          }
          if (this.formData.details.filter(item => !item.moveNum).length > 0) {
            this.$message.warning('调拨数量不能为空')
            return
          }
          if (this.formData.details.filter(item => Number(item.moveNum) > Number(item.stockNum)).length > 0) {
            this.$message.warning('调拨数量不能大于库存数量')
            return
          }
          if (this.formData.details.filter(item => item.moveNum && !this.SETTINGS.reg_no_zero.test(item.moveNum)).length > 0) {
            this.$message.warning('调拨数量未正确填写')
            return
          }
          if (this.formData.details.filter(item => !item.targetWarehouseName).length > 0) {
            this.$message.warning('调入仓库不能为空')
            return
          }
          if (this.formData.details.filter(item => !item.targetLocationId).length > 0) {
            this.$message.warning('调入库位不能为空')
            return
          }
          this.formData.moveTime = this.formData.moveTime ? moment(this.formData.moveTime).format('YYYY-MM-DD') : ''
          addOrUpdate(this.formData).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    save(number) {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.formData.status = number
          if (this.formData.details.length == 0) {
            this.$message.warning('请添加物料明细')
            return
          }
          if (this.formData.details.filter(item => Number(item.moveNum) > Number(item.stockNum)).length > 0) {
            this.$message.warning('调拨数量不能大于库存数量')
            return
          }
          if (this.formData.details.filter(item => item.moveNum && !this.SETTINGS.reg_no_zero.test(item.moveNum)).length > 0) {
            this.$message.warning('调拨数量未正确填写')
            return
          }
          this.formData.moveTime = this.formData.moveTime ? moment(this.formData.moveTime).format('YYYY-MM-DD') : ''
          addOrUpdate(this.formData).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    // 选择仓库
    enterWarehouse(row, index) {
      this.rowIndex = index
      this.$layer.iframe({// 弹框
        content: {
          content: warehouse, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            warehouseId: row.targetWarehouseId ? row.targetWarehouseId : '',
            sparePartId: row.id
          }// props
        },
        area: ['880px', '570px'],
        title: '选择仓库', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    showMaterial(data) {
      this.formData.details = data
      this.formData.details.forEach(ele => {
        delete ele.id
      })
    },
    importSpareParts() { // 导入备件物料
      this.$layer.iframe({// 弹框
        content: {
          content: ImportData, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {}// props
        },
        area: ['440px', '250px'],
        title: '导入数据', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    // 选择仓库回调
    showWarehouse(row, checked) {
      if (checked == false) {
        const arr = this.$deepClone(this.formData.details)
        arr[this.rowIndex].targetWarehouseId = row.id
        arr[this.rowIndex].targetWarehouseName = row.warehouseName
        arr[this.rowIndex].targetLocationId = ''
        arr[this.rowIndex].targetLocationName = ''
        this.targetWarehouseId = row.id
        this.$set(arr, 'targetWarehouseName', row.warehouseName)
        this.formData.details = arr
      } else {
        const arr = this.$deepClone(this.formData.details)
        arr.forEach((item, index) => {
          item.targetWarehouseId = row.id
          item.targetWarehouseName = row.warehouseName
          item.targetLocationId = ''
          item.targetLocationName = ''
          this.targetWarehouseId = row.id
          this.$set(item, 'targetWarehouseName', row.warehouseName)
        })
        this.formData.details = arr
      }
      this.getLocationList({ warehouseId: this.targetWarehouseId, rowIndex: this.rowIndex, checked: checked })
    },
    getLocationList(row) { // 仓库回调触发的方法，用来根据仓库id获取库位
      list({ pageNum: 1, pageSize: 9999, status: 1, warehouseId: row.warehouseId }).then(res => {
        if (row.checked == false) {
          const arr = this.$deepClone(this.formData.details)
          arr[row.rowIndex].locationOptions = []
          res.data.filter(item => {
            if (arr[row.rowIndex].targetWarehouseId ? arr[row.rowIndex].targetWarehouseId : arr[row.rowIndex].warehouseId == item.warehouseId) {
              if (res.data.length == 1) {
                arr[row.rowIndex].targetLocationName = item.locationName
                arr[row.rowIndex].targetLocationId = item.id
              }
              arr[row.rowIndex].locationOptions.push({
                value: item.id,
                label: item.locationName
              })
            }
          })
          this.formData.details = arr
        } else {
          const arr = this.$deepClone(this.formData.details)
          arr.filter(item => {
            item.locationOptions = []
            res.data.filter(ele => {
              if (item.targetWarehouseId == ele.warehouseId) {
                if (res.data.length == 1) {
                  item.targetLocationName = ele.locationName
                  item.targetLocationId = ele.id
                }
                item.locationOptions.push({
                  value: ele.id,
                  label: ele.locationName
                })
              }
            })
          })
          this.formData.details = arr
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.table_container {
  padding-bottom: 20px !important;
  padding-top: 0px !important;
}
</style>
